<template>
    <el-card shadow="never" class="border-0">

        <!-- 搜索 -->
        <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-form-item label="使用平台">
                        <el-select style="width: 100%;" v-model="searchForm.webUse" clearable placeholder="使用平台">
                            <el-option key=0 label="考试系统" value=0></el-option>
                            <el-option key=1 label="官网系统" value=1></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="18">
                    <div class="flex items-center justify-end">
                        <el-button type="primary" @click="initTableData(1)">搜索</el-button>
                        <el-button @click="resetSearchForm">重置</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-form>

        <!-- 新增|刷新 -->
        <div class="flex items-center justify-between mb-4">
            <div>
                <!-- <el-button v-if="developer" type="primary" size="small" @click="handleCreate">新增</el-button> -->
                <el-button type="primary" size="small" @click="handleCreate">新增</el-button>
            </div>

            <el-tooltip effect="dark" content="刷新数据" placement="top">
                <el-button text @click="initTableData">
                    <el-icon :size="20">
                        <Refresh />
                    </el-icon>
                </el-button>
            </el-tooltip>
        </div>

        <!-- 表格数据 -->
        <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">

            <el-table-column label="使用平台" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.webUse == 0 ? '考试系统' : '官网系统' }}
                </template>
            </el-table-column>

            <el-table-column label="排序" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.sort }}
                </template>
            </el-table-column>

            <el-table-column label="证书图片" align="center">
                <template #default="{ row }">
                    <el-image style="width: 60px; height: 60px" :preview-teleported="true" class="images"
                        :hide-on-click-modal=true :src="row.url" :zoom-rate="1.2" :preview-src-list="[row.url]"
                        :initial-index="1" fit="cover">
                    </el-image>
                </template>
            </el-table-column>

            <el-table-column label="创建时间" align="center">
                <template #default="{ row }">
                    {{ dateFormatter(row.createTime) }}
                </template>
            </el-table-column>

            <el-table-column label="操作" width="200" align="center">
                <template #default="scope">
                    <el-button type="primary" size="small" text @click="handleEdit(scope.row)">修改</el-button>
                    <el-popconfirm title="是否要删除该轮播图？" confirmButtonText="确认" cancelButtonText="取消"
                        @confirm="handleDelete(scope.row.id)">
                        <template #reference>
                            <el-button type="primary" size="small" text>删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="flex items-center justify-center mt-5">
            <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
                :page-size="limit" @current-change="initTableData" />
        </div>

        <!-- 新增|修改弹窗 -->
        <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
            <el-form :model="form" ref="formRef" :rules="rules" label-width="120px" :inline="false">
                <el-form-item label="使用者" prop="webUse">
                    <el-radio-group v-model="form.webUse">
                        <el-radio value="0">考试系统</el-radio>
                        <el-radio value="1">官网系统</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="form.sort" placeholder="排序" :min=1></el-input-number>
                </el-form-item>

                <el-form-item label="banner图片" prop="files">
                    <el-upload class="upload-demo" :class="hideUpload ? 'hide' : ''" list-type="picture-card"
                        ref="upload" accept=".jpg,.png" action="" :limit="1" :on-change="fileChange"
                        :file-list="form.files" :before-upload="beforeUpload" :on-exceed="handleExceed"
                        :on-remove="handleRemove" :http-request="uploadSubmit" :auto-upload="false">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>

                <!-- 公司证书没有考试 -->
                <el-form-item v-if="form.templateType == 0" label="证书关联考试" prop="officialExamId">
                    <el-button plain @click="dialogTableVisible_exam = true">
                        {{ null == form.officialExamId ? '未选择' : '已选择' }}
                    </el-button>
                </el-form-item>
            </el-form>
        </FormDrawer>
    </el-card>

    <!-- 选择考试dialog -->
    <SystemDialog title="选择考试" :visible="dialogTableVisible_exam" :height="50" :width="70"
        @on-close="dialogTableVisible_exam = false" @on-confirm="dialogTableVisible_exam = false">
        <template v-slot:content>
            <SelectExam v-if="dialogTableVisible_exam" :showSelection="true" :officialExamId="form.officialExamId"
                @getCheckedExam="getCheckedExam" />
        </template>
    </SystemDialog>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue"
import SystemDialog from "~/components/SystemDialog.vue";
import SelectExam from "~/components/select-exam.vue";
import FormDrawer from "~/components/FormDrawer.vue";
import { toast, toastWarn } from "~/composables/util"
import { dateFormatter } from '~/utils/common.js'
import { api_banner_list, api_banner_add, api_banner_update, api_banner_delete } from "~/api/exam/bannerApi";

// 表格分页数据
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)

// 查询条件
const searchForm = reactive({
    webUse: null,
    page: currentPage.value,
    size: limit.value,
})
// 重置搜索框
const resetSearchForm = () => {
    searchForm.webUse = null
    initTableData(1)
}

// 生命周期函数
onMounted(() => {
    //初始化列表数据
    initTableData()
})

// 表单部分
// 是否是编辑弹窗
const editId = ref(0)
const drawerTitle = computed(() => editId.value ? "修改" : "新增")
const formDrawerRef = ref(null)
const formRef = ref(null)
const form = reactive({
    webUse: "0",
    sort: 1,
    files: [],
})

//执行表单校验
const rules = {
    webUse: [
        { required: true, message: '使用者不能为空', trigger: 'change' }
    ],
    sort: [
        { required: true, message: '排序不能为空', trigger: 'change' }
    ],
    files: [
        { required: true, message: '图片不能为空', trigger: 'change' }
    ],
}


//提交表单
const handleSubmit = () => {
    //表单校验
    formRef.value.validate((valid) => {
        if (!valid) return
        //新增
        if (editId.value == 0) {
            //触发文件上传
            upload.value.submit();
        } else {
            if (editImgChanged.value == true) {
                //触发文件上传
                upload.value.submit();
            } else {
                let paramIo = new FormData()// FormData 对象
                paramIo.append('id', editId.value)
                paramIo.append('webUse', form.webUse)
                paramIo.append('sort', form.sort)
                //loading
                formDrawerRef.value.showLoading()
                const fun = api_banner_update(editId.value, paramIo)
                fun.then(res => {
                    toast(drawerTitle.value + "成功")
                    //清空file文件
                    upload.value.clearFiles();
                    //修改刷新当前页，新增刷新第一页
                    initTableData(editId.value ? false : 1)
                    formDrawerRef.value.close()
                })
                    .finally(() => {
                        //close loading
                        formDrawerRef.value.hideLoading()
                    })
            }
        }
    })
}

// 新增按钮点击事件
const handleCreate = () => {
    //修改标记置为0
    editId.value = 0
    hideUpload.value = false
    resetForm({
        webUse: "0",
        sort: 1,
        files: [],
    })
    //打开弹窗
    formDrawerRef.value.open()
}

// 重置表单
function resetForm(row = false) {
    if (formRef.value) formRef.value.resetFields()
    if (row) {
        for (const key in form) {
            form[key] = row[key]
        }
    }
}

// 上传组件 -------------------------------------------
//上传组件
const upload = ref(null)
const hideUpload = ref(false)
const editImgChanged = ref(false)

// 文件改变
const fileChange = (file, fileList) => {
    form.files = fileList;
    hideUpload.value = true
    editImgChanged.value = true
}
// 文件超出个数限制
const handleExceed = (file, fileList) => {
    toastWarn('只能选择一个文件');
}
// 文件移除
const handleRemove = (file, fileList) => {
    form.files = [];
    hideUpload.value = false
}
// 上传前 文件校验
const beforeUpload = (file) => {
    const isLt2M = file.size / 1024 / 1024 < 10
    if (!isLt2M) {
        toastWarn('上传文件大小不能超过 10MB!')
        return false;
    }
    return true;
}
//提交上的文件
const uploadSubmit = (param) => {
    let fileObj = param.file// 相当于input里取得的files
    let paramIo = new FormData()// FormData 对象
    paramIo.append('id', editId.value)// 主键ID
    paramIo.append('files', fileObj)// 文件对象
    paramIo.append('webUse', form.webUse)
    paramIo.append('sort', form.sort)
    //loading
    formDrawerRef.value.showLoading()
    const fun = editId.value == 0 ? api_banner_add(paramIo) : api_banner_update(editId.value, paramIo)
    fun.then(res => {
        toast(drawerTitle.value + "成功")
        //清空file文件
        upload.value.clearFiles();
        //修改刷新当前页，新增刷新第一页
        initTableData(editId.value ? false : 1)
        formDrawerRef.value.close()
    })
        .finally(() => {
            //close loading
            formDrawerRef.value.hideLoading()
        })
}
// 上传组件 -------------------------------------------


// 获取数据
function initTableData(p = null) {
    //指定页码是否为空
    if (typeof p == "number") {
        currentPage.value = p
    }

    loading.value = true
    searchForm.page = currentPage.value

    api_banner_list(searchForm)
        .then(res => {
            if (res) {
                tableData.value = res.records
                total.value = Number(res.total)
            } else {
                tableData.value = []
                total.value = 0
            }
        })
        .finally(() => {
            loading.value = false
        })
}

// 编辑
const handleEdit = (row) => {
    editId.value = row.id
    resetForm(row)
    //回显图片
    form.files = [{ url: row.url }]
    hideUpload.value = true
    editImgChanged.value = false
    formDrawerRef.value.open()
}

// 删除
const handleDelete = (id) => {
    loading.value = true
    api_banner_delete(id).then(res => {
        toast("删除成功")
        initTableData()
    })
        .finally(() => {
            loading.value = false
        })
}

</script>

<style scoped>
.hide ::v-deep .el-upload--picture-card {
    display: none;
}
</style>